from flask import Blueprint, request
import time
from .db import get_db

fw_update = Blueprint("fw_update",__name__)

@fw_update.route("/fw_update", methods = ["GET", "POST"])
def update():
    sn=request.values.get("sn", "")
    fwver=request.values.get("fwver", "")

    if not sn or not fwver:
        return "Bad Request", 400

    now_date = time.strftime("%Y-%m-%d")

    sn = sn.strip()
    cur_fw = fwver = fwver.strip()

    conn = get_db()
    cur = conn.cursor()

    sql = """select 
        devinfo.fwversion, fwinfo.fwversion, fwinfo.fwurl, devinfo.lastupdate
        from devinfo left join fwinfo 
        on devinfo.isinternal = fwinfo.isinternal
        where devinfo.serial = '%s'""" % (sn,)
    cur.execute(sql)
    rs = cur.fetchall()

    # serial not exists
    if not rs:
        sql = """insert into devinfo(serial, fwversion, firstonline, lastupdate) 
        values ('%s', '%s', now(), now())""" % (sn, fwver)
        cur.execute(sql)

        # trust as publict user, check if need update
        sql = "select fwversion, fwurl from fwinfo where isinternal = 0"
        cur.execute(sql)
        rs = cur.fetchall()
        new_fw = rs[0][0].strip() if rs[0][0] else ""
        fwurl = rs[0][1].strip() if rs[0][1] else ""
        if cur_fw != new_fw:
            msg = "needupdate:1\r\nfwurl:%s\r\nfwver:%s\r\n" % (fwurl, new_fw)
        else:
            msg = "needupdate:0\r\nfwurl:\r\nfwver:\r\n"
    else:
        new_fw = rs[0][1].strip() if rs[0][1] else ""
        fwurl = rs[0][2].strip() if rs[0][2] else ""
        old_fw = rs[0][0].strip() if rs[0][0] else ""
        lastupdate = rs[0][3]

        # check if need update
        if not new_fw or not fwurl:
            # unknow type
            msg = "needupdate:0\r\nfwurl:\r\nfwver:\r\n"
        elif cur_fw != new_fw:
            msg = "needupdate:1\r\nfwurl:%s\r\nfwver:%s\r\n" % (fwurl, new_fw)
        else:
            msg = "needupdate:0\r\nfwurl:\r\nfwver:\r\n"

        # update fwversion, onlinedays, lastupdate
        if not lastupdate:
            sql = """update devinfo set fwversion = '%s', firstonline=now(), lastupdate=now() where serial = '%s'""" % (cur_fw, sn)
        elif lastupdate.strftime("%Y-%m-%d") == now_date:
            sql = """update  devinfo set fwversion = '%s', lastupdate=now() where serial = '%s'""" % (cur_fw, sn)
        else:
            sql = """update  devinfo set fwversion = '%s', lastupdate=now(), onlinedays = onlinedays + 1 where serial = '%s'""" % (cur_fw, sn)
        cur.execute(sql)
        conn.commit()

    # check if on deviceonline table
    sql = "select id from deviceonline where serial = '%s' and recorddate = '%s'" % (sn, now_date)
    cur.execute(sql)
    rs = cur.fetchall()
    if not rs:
        sql = "insert into deviceonline (serial, recorddate) values('%s', '%s')" % (sn, now_date)
        cur.execute(sql)
        conn.commit()

    cur.close()
    return msg,200,{"Content-Type":"text/plain"}

